package com.xpu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xpu.reggie.common.CustomerException;
import com.xpu.reggie.dto.SetmealDto;
import com.xpu.reggie.entity.Setmeal;
import com.xpu.reggie.entity.SetmealDish;
import com.xpu.reggie.mapper.SetmealMapper;
import com.xpu.reggie.service.SetmealDishService;
import com.xpu.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1. 保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        //2. 补全套餐菜品关系
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));

        //3. 保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     */
    @Override
    @Transactional
    public void removeWithDish(Long[] ids) {
        //1. 查询套餐状态，确定是否可用删除 SQL：select count(*) from setmeal where id in (1,2,3) and status = 1
        QueryWrapper<Setmeal> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id", Arrays.asList(ids));
        queryWrapper1.eq("status", 1);
        int count = this.count(queryWrapper1);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomerException("套餐正在售卖，不能删除");
        }

        //2.1 如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(Arrays.asList(ids));

        //2.2 删除关系表setmeal_dish中的数据----SQL：delete from setmeal_dish where setmeal_id in (1,2,3)
        QueryWrapper<SetmealDish> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("setmeal_id", Arrays.asList(ids));
        setmealDishService.remove(queryWrapper2);
    }
}